<?php
/**
 * Created by PhpStorm.
 * Script Name: TemplateMsg.php
 * Create: 2023/1/11 18:29
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\queue;

use plugin\wechat\app\service\BotFriend as FriendService;
use plugin\wechat\app\service\BotGroup as GroupService;
use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\model\Bot as BotM;
use plugin\wechat\app\model\BotTjgroup as TjGroupM;
use plugin\wechat\app\service\BotReply as ReplyService;
use plugin\wechat\app\service\BotMoments as MomentsService;
use plugin\wechat\app\model\BotMomentsFollow as MomentsFollowM;

class Bot
{
    public function __construct()
    {

    }

    /**
     * 跟圈
     * Author: fudaoji<fdj@kuryun.cn>
     * @param array $params
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function followMoments($params = []){
        $task = $params['task'];
        try {
            $bot_info = BotService::getBot($task['bot_id'], $task['company_id']);
            $client = BotService::getRobotClient($bot_info);
            $wxid_arr = explode(',', $task['wxids']);
            foreach ($wxid_arr as $wxid){
                $res = $client->getFriendMoments([
                    'robot_wxid' => $bot_info['uin'],
                    'to_wxid' => $wxid,
                    'num' => 1
                ]);
                if(empty($res['data'])){
                    continue;
                }

                $list = $res['data'];
                foreach ($list as $item){
                    $timeline = MomentsService::decodeObject($item['object']);
                    if(strtotime($timeline['create_time']) > $task['last_time']){
                        $client->sendMomentsXml([
                            'robot_wxid' => $bot_info['uin'],
                            'xml' => $item['object']
                        ]);
                    }
                }
            }

            MomentsFollowM::update(['id' => $task['id'], 'last_time' => time()]);
        }catch (\Exception $e){
            var_dump('跟圈队列任务出错：');
            var_dump($e->getMessage());
            dao_log()->error($e->getMessage());
        }
    }

    /**
     * 批量发送消息
     * @param array $params
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function sendMsgBatch($params = []){
        $task = $params['task'];
        $client = BotService::getRobotClient($task);
        $reply = $params['reply'];
        $to_wxid = $params['to_wxid'];
        $extra = $params['extra'];
        ReplyService::botReply($task, $client, $reply, $to_wxid, $extra);
    }

    /**
     * 拉取通讯录
     * @param array $data
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function pullMembers($data = []){
        $bot = BotService::getBot($data['bot']['id'], $data['bot']['company_id']);
        FriendService::pullFriends($bot);
        GroupService::pullGroups($bot);
    }

    /**
     * 群成员增减统计
     * Author: fudaoji<fdj@kuryun.cn>
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function tjGroup($data = []){
        $field = $data['type'] == 'add' ? 'add_num' : 'decr_num';
        if(! $tj = TjGroupM::where([
            ['company_id' ,'=', $data['company_id']],
            ['group_id' ,'=', $data['group_id']],
            ['day' ,'=', $data['day']]
        ])->find()){
            $bot = BotM::find($data['bot_id']);
            $insert = [
                'company_id' => $bot['company_id'],
                'group_id' => $data['group_id'],
                'day' => $data['day'],
                'bot_id' => $data['bot_id'],
                $field => 1
            ];
            TjGroupM::create($insert);
        }else{
            TjGroupM::update(['id' => $tj['id'],  $field => $tj[$field] + 1]);
        }
    }
}